package com.wms.shop.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.google.common.collect.Maps;
import com.wms.common.core.utils.DateUtils;
import com.wms.common.security.service.TokenService;
import com.wms.shop.api.model.WxLoginUser;
import com.wms.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.Objects;

/**
 * 填充器
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Autowired
    private TokenService tokenService;

    @Override
    public void insertFill(MetaObject metaObject) {

        log.info("start insert fill ....");
        Map map = getLoginMap();
        if (Objects.isNull(metaObject.getValue("createBy"))) {
            metaObject.setValue("createBy", map.get("userName"));
        }
        if (Objects.isNull(metaObject.getValue("createTime"))) {
            metaObject.setValue("createTime", DateUtils.getNowDate());
        }
        if (Objects.isNull(metaObject.getValue("delFlag"))) {
            metaObject.setValue("delFlag", 0);
        }
        if (metaObject.hasGetter("tenantId") && Objects.isNull(metaObject.getValue("tenantId"))) {
            metaObject.setValue("tenantId", map.get("tenantId"));
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        Map map = getLoginMap();
        metaObject.setValue("updateBy", map.get("userName"));
        metaObject.setValue("updateTime", DateUtils.getNowDate());
    }


    public Map getLoginMap() {
        Map map = Maps.newHashMap();
        // 区分微信和pc登录
        String userName = null;
        Long tenantId = null;
        Object obj = tokenService.getLoginUser();
        if (obj != null && obj instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) obj;
            tenantId = loginUser.getTenantId();
            userName = loginUser.getUsername();
        } else if (obj != null && obj instanceof WxLoginUser) {
            WxLoginUser wxLoginUser = (WxLoginUser) obj;
            tenantId = wxLoginUser.getTenantId();
            userName = wxLoginUser.getUsername();
        }
        map.put("userName", userName);
        map.put("tenantId", tenantId);
        return map;
    }

}